package com.eascs.spider.yuqing.schdule.register;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.eascs.spider.yuqing.common.util.RandomUtil;
import com.eascs.spider.yuqing.common.util.ZKUtil;

/**
 * 注册中心,从zookeeper定时更新工作节点信息
 * @author hzp
 *
 */
@Service
public class RegisterCentre {

	private static Logger logger = LoggerFactory.getLogger(RegisterCentre.class);
	private volatile List<String> workerList = new ArrayList<>();//工作节点在此注册,ip:port
	
	public RegisterCentre() {
		Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new Runnable() {
			
			@Override
			public void run() {
				try {
					workerList = ZKUtil.getRegisterInfo();
				} catch (Exception e) {
					logger.error("注册中心从zk更新工作节点信息发生异常" ,e);
				}
			}
		}, 1, 5, TimeUnit.SECONDS);
	}
	
	//随机获取一个工作节点
	public String getRandomWorkerAddress(){
		return workerList.get(RandomUtil.nextInt(workerList.size()));
	}
	
	public List<String> getWorkers(){
		return workerList;
	}
	
}
